package com.chen.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

public class logFilter implements Filter {

    /**
     * 每次拦截到的请求都会执行这个方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 访问资源之前执行的方法
        servletResponse.setContentType("text/html;charset=UTF-8");
        System.out.println("拦截到了请求");

        // 打印访问日志
        System.out.println(request.getRequestURI() + " 访问了" + "时间" + LocalDateTime.now().toLocalTime());

        // 放行操作
        long bight = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        long end = System.currentTimeMillis();
        // 响应数据之前执行的方法 对响应数据进行处理

        System.out.println(request.getRequestURL() + "访问耗费了" + (end - bight) + "毫秒");

    }
}
